package com.talkweb.demo.search;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Scanner;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2024/10/10
 */
public class TxtSearch {
    private final static Logger log = LoggerFactory.getLogger(TxtSearch.class);

    private static String txt = null;
    private static String source = null;
    private static String target = null;
    private static String keyword = null;
    private static String[] keywords = null;

    public static void search(Scanner scanner) {
        params(scanner);
        File txtFile = new File(txt);
        File[] files = txtFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            log.info("开始处理第[" + (i + 1) + "/" + files.length + "]个文件:" + file);
            if (file.isFile() && file.getName().endsWith(".txt")) {
                begin(file);
            } else {
                log.error("不处理目录和非.txt文件：" + file.getAbsolutePath());
            }
        }
    }

    private static void params(Scanner scanner) {
        while (null == txt) {
            System.out.print("规范化后的txt目录：");
            String input = scanner.nextLine();
            if (StrUtil.isNotBlank(input)) {
                input = input.trim();
                File file = new File(input);
                if (file.exists()) {
                    if (file.isDirectory()) {
                        txt = input;
                    } else {
                        System.err.println("！！必须是目录，不能直接指定文件！！");
                    }
                }
            }
        }

        while (null == source) {
            System.out.print("真实pdf目录：");
            String input = scanner.nextLine();
            if (StrUtil.isNotBlank(input)) {
                input = input.trim();
                File file = new File(input);
                if (file.exists()) {
                    if (file.isDirectory()) {
                        source = input;
                    } else {
                        System.err.println("！！必须是目录，不能直接指定文件！！");
                    }
                }
            }
        }

        while (null == target) {
            System.out.print("命中后移动到目录：");
            String input = scanner.nextLine();
            if (StrUtil.isNotBlank(input)) {
                input = input.trim();
                if (input.equalsIgnoreCase(source)) {
                    System.err.println("！！移动到的目录不能与搜索目录相同！！");
                } else {
                    target = input;
                }
            }
        }

        while (null == keyword) {
            System.out.print("搜索关键字，多个用英文逗号隔开：");
            String input = scanner.nextLine();
            if (StrUtil.isNotBlank(input)) {
                input = input.trim();
                keyword = input;
                keywords = input.split(",");
            }
        }

        System.out.println("=======================================================");
        System.out.println("规范化后的txt目录：" + txt);
        System.out.println("真实pdf目录：" + source);
        System.out.println("命中后移动到目录：" + target);
        System.out.println("搜索关键字：" + keyword);
        System.out.println("=======================================================");

        System.out.print("是否确认开始（y/n）[y]：");
        String input = scanner.nextLine();
        scanner.close();
        if (StrUtil.isNotBlank(input) && !"y".equalsIgnoreCase(input)) {
            System.exit(0);
        }
    }

    private static void begin(File txtFile) {
        String sourceFileAbsolutePath = txtFile.getAbsolutePath();
        if (FileCacheUtil.exists(sourceFileAbsolutePath)) {
            log.info("==== 已处理过的文件，不重复处理:" + sourceFileAbsolutePath + " ====");
            return;
        }
        String realName = txtFile.getName().substring(0, txtFile.getName().lastIndexOf("."));
        String realPdfName = source + File.separator + realName + ".pdf";

        String content = FileUtil.readUtf8String(txtFile);
        boolean contains = SearchUtil.contains(content, keywords);
        if (contains) {
            File realFile = new File(realPdfName);
            if (!realFile.exists()) {
                log.error("pdf文件不存在：" + realPdfName);
                return;
            }
            File targetFile = new File(target + File.separator + realFile.getName());
            if (targetFile.exists()) {
                log.error("目标路径已存在，不做任何操作：" + targetFile.getAbsolutePath());
                return;
            }
            log.info(" =================命中：" + realPdfName);
            targetFile.getParentFile().mkdirs();
            FileUtil.move(realFile, targetFile, false);
        } else {
            log.info(" ====未命中" + realPdfName);
        }
        FileCacheUtil.cache(sourceFileAbsolutePath);
    }
}
